import { lazy, Suspense } from 'react';
import { createBrowserRouter } from 'react-router-dom';

import Layout from '@/components/Layout';
import Login from '@/views/Login';

const modules = import.meta.glob('../views/**/(*.page.tsx|page.tsx)');
type MenuItem = { label: string; path: string;key:string, children?: MenuItem[] };
export const menu: MenuItem[] = [];

const children = Object.keys(modules).map((path) => {
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  // @ts-expect-error
  const Widget = lazy(modules[path]);

  path = path
    .replace('../views', '')
    .replace(/\.page\.tsx$/, '')
    .replace(/page\.tsx$/, '')
  

  const titles = path.split('/')

  if (!titles[0]) {
    titles.shift()
  }


  function setMenu(menu:MenuItem[], titles: string[],path: string,level=1){
    const title = titles.shift() || ''
    let item = menu.find(t=>t.label === title)
    if (!item) {
      item = {
        label:title || path.split('/').filter(Boolean).slice(0, level).join('/'),
        path: path,
        key: path,
      }
      menu.push(item)
    }
    if (titles.length) {
      item.children = item.children ?? []
      item.key = path.split('/').filter(Boolean).slice(0, level).join('/')
      setMenu(item.children, titles, path, level+1)
    }
  }
  setMenu(menu, titles, path)
  return {
    path,
    element: (
      <Suspense fallback={null}>
        <Widget />
      </Suspense>
    ),
  };
});


function clearOneChildren(menu:MenuItem[]){
  menu.forEach(item=>{
    if (item.children && item.children.length === 1) {
      item.key = item.children[0].key
      item.children = item.children[0].children
    }
  })
}
clearOneChildren(menu)

const router = createBrowserRouter(
  [
    {
      path: '/login',
      element: <Login />,
      children: [],
    },
    {
      path: '/',
      element: <Layout />,
      children: children,
    },
  ],
  { basename: import.meta.env.BASE_URL }
);

export default router;
